<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use fast\Random;
use app\admin\model\Agent as AgentModel;
use think\Db;
use think\Exception;
use app\admin\validate\User;
use app\admin\model\Wallet;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class Agent extends Backend
{

    protected $relationSearch = true;
    protected $modelValidate = false;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            $pid = $this->request->get('pid') ? : 0;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['group','grade','wallet'])
                ->where($where)
                ->where(function ($q) use($pid) {
                    if( $pid && $pid > 0 ){
                        $q->where('pid',$pid);
                    }else{
                        $q->where('group_id',3);
                    }
                })
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with(['group','grade','wallet'])
                ->where($where)
                ->where(function ($q) use($pid) {
                    if( $pid && $pid > 0 ){
                        $q->where('pid',$pid);
                    }else{
                        $q->where('group_id',3);
                    }
                })
                ->join('dj_agent a','a.user_id=dj_user.id','left')
                ->field('a.rebateNum,a.code')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            if( $pid && $pid > 0 ){
                $total = $this->model
                    ->with(['group','grade','wallet'])
                    ->where(function ($q) use($pid) {
                        if( $pid && $pid > 0 ){
                            $q->where('pid',$pid);
                        }else{
                            $q->where('group_id',3);
                        }
                    })
                    ->order($sort, $order)
                    ->count();
                $list = $this->model
                    ->with(['group','grade','wallet'])
                    ->where(function ($q) use($pid) {
                        if( $pid && $pid > 0 ){
                            $q->where('pid',$pid);
                        }else{
                            $q->where('group_id',3);
                        }
                    })
                    ->join('dj_agent a','a.user_id=dj_user.id','left')
                    ->field('a.rebateNum,a.code')
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            }

            foreach ($list as $k => $v)
            {
                $v->hidden(['password', 'salt']);
                $list[$k]['grade'] = '层级';
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     * @throws Exception
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $time = time();
            $ip = request()->ip();
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }

                    $validate = new User();
                    if( !$validate->scene('add')->check($params) ){
                        $this->error($validate->getError());
                    }

                    $params = array_merge($params, [
                        'salt'      => Random::alnum(),
                        'jointime'  => $time,
                        'joinip'    => $ip,
                        'logintime' => $time,
                        'loginip'   => $ip,
                        'prevtime'  => $time,
                        'status'    => 'normal'
                    ]);
                    $params['password_confirm'] = md5(md5($params['password']) . $params['salt']);
                    $params['password'] = md5(md5($params['password']) . $params['salt']);

                    $result = (new \app\admin\model\User)->allowField(true)->save($params);
                    $user_id =(new \app\admin\model\User)->where('username',$params['username'])->value('id');

                    AgentModel::insert([
                        'rebateNum' => $params['rebateNum'],
                        'user_id'   => $user_id,
                        'code'      => $this->code()
                    ]);

                    $salt = random(6);
                    //插入钱包
                    $wallet = new Wallet;
                    $wallet->user_id    = $user_id;
                    $wallet->money      = 0.00; //钱包余额
                    $wallet->salt       = $salt;
                    $wallet->pay_password = md5(md5($params['username']) . $salt); //密码默认为账号，记得修改
                    $wallet->site       = '';
                    $wallet->save();

                    Db::commit();
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }

                } catch (\think\exception\PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     * @throws Exception
     */
    public function edit($ids = NULL)
    {
        $this->modelValidate = false;
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));


        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $validate = new User();
                    if( !$validate->scene('edit')->check($params) ){
                        $this->error($validate->getError());
                    }
                    $result = $row->allowField(true)->save($params);
                    $agent = AgentModel::where('user_id',$ids)->find();
                    if( $agent ){
                        $agent->rebateNum = $params['rebateNum'];
                        $agent->save();
                    }else{
                        AgentModel::insert([
                            'user_id'   => $ids,
                            'rebateNum' => $params['rebateNum'],
                            'code'      => $this->code()
                        ]);
                    }

                    Db::commit();
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $rebateNum = AgentModel::where('user_id',$ids)->value('rebateNum');
        $this->view->assign('rebateNum',$rebateNum);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     * @param string $ids
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model
                ->where($pk, 'in', $ids)
                ->select();
            $count = 0;
            Db::startTrans();
            try{
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                    AgentModel::where('user_id',$v['id'])->delete();
                    Wallet::where('user_id',$v['id'])->delete();
                }

                Db::commit();
                if ($count) {
                    $this->success();
                } else {
                    $this->error(__('No rows were deleted'));
                }
            }catch (Exception $e){
                Db::rollback();
                $this->error($e->getMessage());
            }

        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    public function code(){
        $code = Random::numeric(6);
        $count = AgentModel::where('code',$code)->count();
        if( $count && $count > 0 ){
            $this->code();
        }
        return $code;
    }

}
